<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>组织架构</title>
  <!-- import CSS -->
  <link rel="shortcut icon" href="../favicon.ico">
  <link rel="stylesheet" href="../plugins/ElementUI/index-2.3.9.css">
  <link href="../css/common.css" rel="stylesheet">
  <!-- import Vue before Element -->
  <script src="../plugins/ElementUI/vue-2.5.16.js"></script>
  <!-- import JavaScript -->
  <script src="../plugins/ElementUI/index-2.3.9.js"></script>
  <script src="../plugins/ElementUI/vue-resource.min.js"></script>
  <!-- link bootstrap -->
  <link rel="stylesheet" href="../css/bootstrap.min14ed.css">
  <link rel="stylesheet" href="../css/style.min862f.css">
  <style>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
  </style>
</head>
<body class="gray-bg">
  <div id="appa" v-cloak v-show="appShow" class="animated fadeInRight">
      <div class="wrapper wrapper-content">
          <div class="row">
              <div class="col-sm-3">
                  <div class="ibox float-e-margins">
                      <div class="ibox-title">
                          <h5>公司车队列表</h5>
                      </div>
                      <div class="ibox-content">
                            <el-tree
                                :props="defaultProps"
                                :data="treeData"
                                node-key="id"
                                ref="tree"
                                @node-click="nodeClick"
                                :default-expanded-keys="[0]"
                                :expand-on-click-node="false">
                                <span class="custom-tree-node" slot-scope="{ node, data }">
                                    <span>{{ node.label }}</span>
                                    <span>
                                        <el-button
                                            type="text"
                                            size="mini"
                                            @click.stop.prevent="() => append(node, data)"
                                            v-show="resourceMap.addDepartment">
                                            新增
                                        </el-button>
                                        <el-button
                                            type="text"
                                            size="mini"
                                            @click.stop.prevent="() => editor(node, data)"
                                            v-show="resourceMap.updateDepartment">
                                            编辑
                                        </el-button>
                                        <el-button
                                            type="text"
                                            size="mini"
                                            @click.stop.prevent="() => remove(node, data)"
                                            v-show="resourceMap.deleteDepartment">
                                            删除
                                        </el-button>
                                    </span>
                                </span>
                            </el-tree>
                      </div>
                  </div>
              </div>
              <div class="col-sm-4">
                  <div class="ibox float-e-margins">
                      <div class="ibox-title">
                          <h5>已分配车辆</h5>
                      </div>
                      <div class="ibox-content">
                            <el-table :data="tableDataED.list" style="width: 100%" size="mini" @selection-change="handleSelectionChangeED" :row-key="getRowKeysED" ref="multipleTableED">
                                <el-table-column
                                    type="selection"
                                    :reserve-selection="true"
                                    width="55">
                                </el-table-column>
                                <el-table-column
                                    prop="plateNo"
                                    label="车牌号"
                                    width="80">
                                </el-table-column>
                                <el-table-column
                                    prop="vinCode"
                                    label="车架号">
                                </el-table-column>
                                <el-table-column
                                    label="所属组织"
                                    width="120">
                                    <template slot-scope="scope">
                                        <span>{{departmentNameED}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div style="margin:15px 0"></div>
                            <el-pagination
                                background
                                small
                                layout="prev, pager, next"
                                @current-change="currentChangeED"
                                :current-page="pageParamED.page"
                                :total="tableDataED.totalCount">
                            </el-pagination>
                      </div>
                  </div>
              </div>
              <div class="col-sm-1" style="text-align:center" v-show="resourceMap.allocateVehicle">
                  <p><el-button size="small" type="primary" plain @click="toggleMobile('in')" icon="el-icon-d-arrow-left">移至车队</el-button></p>
                  <p><el-button size="small" type="primary" plain @click="toggleMobile('out')">移出车队 <i class="el-icon-d-arrow-right"></i></el-button></p>
              </div>
              <div class="col-sm-4">
                  <div class="ibox float-e-margins">
                      <div class="ibox-title">
                          <h5>未分配车辆</h5>
                      </div>
                      <div class="ibox-content">
                            <el-table :data="tableDataBEEN.list" style="width: 100%" size="mini" @selection-change="handleSelectionChangeBEEN" :row-key="getRowKeysBEEN" ref="multipleTableBEEN">
                                <el-table-column
                                    type="selection"
                                    :reserve-selection="true"
                                    width="55">
                                </el-table-column>
                                <el-table-column
                                    prop="plateNo"
                                    label="车牌号"
                                    width="80">
                                </el-table-column>
                                <el-table-column
                                    prop="vinCode"
                                    label="车架号">
                                </el-table-column>
                                <el-table-column
                                    prop="online"
                                    label="是否在线"
                                    width="80">
                                </el-table-column>
                            </el-table>
                            <div style="margin:15px 0"></div>
                            <el-pagination
                                background
                                small
                                layout="prev, pager, next"
                                @current-change="currentChangeBEEN"
                                :current-page.sync="pageParamBEEN.page"
                                :total="tableDataBEEN.totalCount">
                            </el-pagination>
                      </div>
                  </div>
              </div>              
          </div>
      </div>
        <!-- 车队编辑弹出框 -->
        <div class="modal inmodal fade" id="myModal" tabindex="-1" role="dialog"  aria-hidden="true">
            <div class="modal-dialog modal-md">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" v-show="controlStatus == 'append'">新增组织</h4>
                        <h4 class="modal-title" v-show="controlStatus == 'editor'">编辑组织</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal m-t">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">部门名称：</label>
                                <div class="col-sm-8">
                                    <input v-model="controlData.departmentName" minlength="2" type="text" class="form-control" required="" autocomplete="off">
                                    <p></p>
                                    <el-alert title="请填写本门名称（不能为空）" type="error" show-icon :closable="false" v-show="elAlert"></el-alert>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="col-sm-3 control-label">部门类型：</label>
                                <div class="col-sm-8">
                                    <select class="form-control" v-model="controlData.departmentType">
                                        <option v-for="option in options" :value="option.value">{{option.text}}</option>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" @click.prevent="saveUpdate">保存</button>
                    </div>
                </div>
            </div>
        </div>
  </div>
</body>
  <script src="../plugins/Underscore/underscore-min.js"></script>
  <script src="../js/ApiRequest.js"></script>
  <script src="../js/jquery.min.js"></script>
  <script src="../js/bootstrap.min.js"></script>
  <script>
      /**
       * departmentName -- 部门名称
       * departmentType -- 部门类型 (1：4s店,0：直营店)
       * leaf           -- 是否是最后一级菜单(1：不是最后一级，0：是最后一级&&没有子菜单)
       * pid            -- 父级菜单主键
      */
    var vm = new Vue({
      el: '#appa',
      data: function() {
        return { 
            appShow:true,
            resourceMap:storageLocal.getName('organize'),
            windowHeight: (window.innerHeight||(document.documentElement&&document.documentElement.clientHeight)||document.body.clientHeight) - 220,
            elAlert:false,
            id:1000,
            treeData:[],
            treeTemporary:{},//tree node 结构
            controlData:{
                departmentName:"",//	部门名称
                departmentType:1,//	部门类型 1：4S店
                id:null,//记录主键
                pid:null//父级菜单主键
            },
            controlStatus:'',
            options: [
                { text: '4s店', value: 1 },
                { text: '其他', value: 0 },
            ],
            defaultProps:{
                children: 'childDepartment',
                label: 'departmentName',
                isLeaf:'lastLeaf',
                type:'departmentType'
            },
            multipleSelectionED:[],//已选中的已分配车辆
            multipleSelectionBEEN:[],//已选中的未分配车辆
            departmentNameED:"",//已分配组织名称
            tableDataED: [],
            tableDataBEEN:[],
            pageParamED:{
                departmentId:"",
                page:1,
                pageSize:10
            },
            pageParamBEEN:{
                page:1,
                pageSize:10
            }
        }
      },
      mounted:function(){
        this.$nextTick(function(){
          this.queryDepartmentTreeList()
        })
      },
      updated:function(){
        this.appShow = true
      },
      methods: {
        queryDepartmentTreeList(){
            var _this = this;
            resourceRequst("/department/queryDepartmentTreeList",{id:0},function(res){
                _this.treeData = [{ 
                    departmentName: '上海同捷',
                    departmentType:1,
                    id: 0,
                    childDepartment:res.resultList
                }]
            },true)
        },
        requestTreeData:function(id,callback){
            var data = {
                id: id || "0"
            }
            resourceRequst("/department/queryDepartmentList",data,function(res){
                if(typeof callback == "function")  callback(res.resultList)
            },true)
        },
        // 异步加载树===》目前被弃用
        loadNode(node, resolve) { 
            let treeData ;
            if (node.level === 0) {
                treeData = [{ 
                    departmentName: '上海同捷',
                    departmentType:1,
                    id: 0,
                    children:[]
                }]
                return resolve(treeData)
                
            }
            if(node.level == 1){
                setTimeout(()=>{
                    this.requestTreeData(null,function(child){
                        return resolve(child)
                    })
                },500)
            }
            console.log("queryDepartmentList",node.data)
            if (node.level > 1) {
                setTimeout(()=>{
                    this.requestTreeData(node.data.id,function(child){
                        return resolve(child)
                    })
                },500)
            }
            //return resolve([]);

            // if (node.level === 0) {
            //     return resolve([{ 
            //         departmentName: '上海同捷',
            //         departmentType:1,
            //         lastLeaf:false, 
            //         pid: 0,
            //     }]);
            // }
            // if(node.level == 1){
            //     setTimeout(()=>{
            //         this.requestTreeData(null,function(child){
            //             return resolve(child);
            //         })
            //     },500)
            // }
            // if (node.level > 1) return resolve([]);

            
        },
        append(node, data) {      
            this.controlStatus = 'append';
            this.elAlert = false;
            this.treeTemporary = { node:node,  data:data }
            this.controlData = {
                departmentName:"",
                departmentType:1,
                pid:data.id,
            }
            $('#myModal').modal('show');

        },
        editor(node, data){
            this.treeTemporary = {
                node:node, 
                data:data
            };
            this.controlStatus = 'editor';
            this.elAlert = false;
            this.controlData = {
                ...data
            }
            $('#myModal').modal('show');
        },
        remove(node, data) {
            var _this = this;
            var _data = data;
            this.$alert('此操作将删除选中数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              showCancelButton:true,
              type: 'warning',
              callback: function(action){
                if (action == "confirm") {
                  var data = {departmentId:_data.id}                  
                  resourceRequst("/department/deleteDepartment",data,function(res){
                    
                      _this.controlStatus = 'remove';
                      const parent = node.parent;
                      const children = parent.data.childDepartment || parent.data;
                      const index = children.findIndex(d => d.id === data.id);
                      children.splice(index, 1);

                    _this.$message({ type: 'success', message: "删除成功！" });
                  })
                }
              }
            });
        },
        saveUpdate(){
            const {node, data} = this.treeTemporary;
            var name = this.controlData.departmentName;
            name = name.replace(/\s*/g,"");
            if(!name.length){
                this.elAlert = true;
                return
            } 
            //编辑组织
            if(this.controlStatus == 'editor'){
                const spliceData = {
                    departmentName:this.controlData.departmentName,
                    departmentType:this.controlData.departmentType,
                    lastLeaf:this.controlData.lastLeaf
                };
                resourceRequst("/department/updateDepartment", this.controlData,function(res){
                    const parent = node.parent;
                    const children = parent.data.childDepartment || parent.data;
                    const index = children.findIndex(d => d.id === data.id); 

                    children[index].departmentName = spliceData.departmentName;
                    children[index].departmentType = spliceData.departmentType;

                    $('#myModal').modal('hide');
                })
            }
            //新增组织
            if(this.controlStatus == 'append'){
                var _this = this;
                resourceRequst("/department/addDepartment", this.controlData,function(res){
                    const newChild = res.departmentEntity;
                    if (!data.childDepartment) {
                        _this.$set(data, 'childDepartment', []);
                    }
                    data.childDepartment.push(newChild);

                    $('#myModal').modal('hide');
                })
            }
        },
        // tree 选中行
        nodeClick(data){
            console.log(data)
            const param = {
                departmentId:data.id,
                page:1,
                pageSize:10
            };
            const _this = this;
            this.pageParamED.departmentId = data.id;
            this.pageParamED.page = 1;
            this.pageParamBEEN.page = 1;

            this.departmentNameED = data.departmentName;

            this.removeSelectionED()
            this.removeSelectionBEEN()

            resourceRequst("/department/queryVehicleListInDepartment",param,function(res){
                _this.tableDataED = res
            },true)
            resourceRequst("/department/queryVehicleListNotInDepartment",param,function(res){
                _this.tableDataBEEN = res
            })
        },
        /**
        **  已分配车辆
        **removeSelectionED == 取消选中
        **currentChangeED == 分页切换
        **/         
        handleSelectionChangeED(val) {
            this.multipleSelectionED = val;
        },
        getRowKeysED(row) {
            return row.id;
        },
        currentChangeED(val){        
            const param = {
                departmentId:this.pageParamED.departmentId,
                page:val,
                pageSize:this.pageParamED.pageSize
            };
            this.pageParamED = param;
            var _this = this;
            resourceRequst("/department/queryVehicleListInDepartment",param,function(res){
                _this.tableDataED = res
            },true)
        },
        removeSelectionED() {
            this.$refs.multipleTableED.clearSelection();
        },
        /**
        **  未分配车辆
        **/ 
        handleSelectionChangeBEEN(val) {
            this.multipleSelectionBEEN = val;
        },
        getRowKeysBEEN(row) {
            return row.id;
        },
        currentChangeBEEN(val){        
            const param = {
                page:val,
                pageSize:this.pageParamBEEN.pageSize
            };
            this.pageParamBEEN = param;
            var _this = this;
            resourceRequst("/department/queryVehicleListNotInDepartment",param,function(res){
                _this.tableDataBEEN = res
            },true)
        },
        removeSelectionBEEN() {
            this.$refs.multipleTableBEEN.clearSelection();
        },
        // 移动车辆
        toggleMobile(flag){
            var _this = this;
            if(flag && flag == "in"){
                var list = this.multipleSelectionBEEN.map(item => item.id);
                if(list && Object.keys(list).length){
                    var param = {
                        departmentId:this.pageParamED.departmentId,
                        vehicleIdList:list
                    }
                    resourceRequst("/department/allocateVehicle",param,function(res){
                    console.log(res)
                    _this.nodeClick({id:_this.pageParamED.departmentId,departmentName:_this.departmentNameED})
                    return
                    })
                }else{
                    this.$notify({
                        title: '警告',
                        message: '请勾选分配车辆',
                        type: 'warning'
                    });
                }
            }
            if(flag && flag == "out"){
                var list = this.multipleSelectionED.map(item => item.id);
                if(list && Object.keys(list).length){
                    var param = {
                        departmentId:0,
                        vehicleIdList:list
                    }
                    resourceRequst("/department/allocateVehicle",param,function(res){
                    console.log(res)
                    _this.nodeClick({id:_this.pageParamED.departmentId,departmentName:_this.departmentNameED})
                    return
                    })
                }else{
                    this.$notify({
                        title: '警告',
                        message: '请勾选分配车辆',
                        type: 'warning'
                    });
                }
                
            }
            return 
        }
      }
    })
  </script>
</html>